package com.zy.db.utils;

import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class DataSourceUtils {

    /**
     * 数据库连接测试
     *
     * @param code
     * @param username
     * @param password
     * @param url
     * @param driver
     * @return
     */
    private static boolean testConnection(String code, String username, String password, String url, String driver) {
        log.info("test connection start. code:{}", code);
        Connection var2 = null;
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            log.warn("class not found. code: {}", code, e);
            return false;
        }
        try {
//            JdbcSecurityUtil.validate(url);
            DriverManager.setLoginTimeout(3);
            var2 = DriverManager.getConnection(url, username, password);
            if (var2 == null) {
                log.warn("connection fail. code: {}", code);
                return false;
            }
            log.info("test connection success. code:{}", code);
        } catch (Exception e) {
            log.warn("connection error. code: {}", code, e);
            return false;
        } finally {
            try {
                if (var2 != null && !var2.isClosed()) {
                    var2.close();
                }
            } catch (SQLException e) {
                log.warn(e.toString());
            }
        }
        return true;
    }

    public static Map<String, Object> ResultSetToMap(ResultSet resultSet, String key, String value) throws SQLException {
        Map<String, Object> map = new HashMap<>();
        while (resultSet.next()) {
            map.put(resultSet.getString(key), resultSet.getString(value));
        }
        return map;
    }
}
